using Microsoft.AspNetCore.Mvc;
using RAG.Application.Services.Interfaces;
using RAG.Application.Dtos.User;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly ILogger<UserController> _logger;

    public UserController(IUserService userService, ILogger<UserController> logger)
    {
        _userService = userService;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有用户
    /// </summary>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<UserDto>>> GetAllUsers()
    {
        try
        {
            var users = await _userService.GetAllAsync();
            return Ok(users);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取用户列表失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 根据ID获取用户
    /// </summary>
    [HttpGet("{id}")]
    public async Task<ActionResult<UserDto>> GetUserById(Guid id)
    {
        try
        {
            var user = await _userService.GetUserByIdAsync(id);
            if (user == null)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return Ok(user);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取用户失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    [HttpPost]
    public async Task<ActionResult<UserDto>> CreateUser([FromBody] UserDto userDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var createdUser = await _userService.CreateUserAsync(userDto);
            return CreatedAtAction(nameof(GetUserById), new { id = createdUser.Id }, createdUser);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "创建用户失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    [HttpPut("{id}")]
    public async Task<ActionResult<UserDto>> UpdateUser(Guid id, [FromBody] UserDto userDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var updatedUser = await _userService.UpdateUserAsync(id, userDto);
            return Ok(updatedUser);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "更新用户失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteUser(Guid id)
    {
        try
        {
            var result = await _userService.DeleteUserAsync(id);
            if (!result)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return NoContent();
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "删除用户失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 获取用户的角色列表
    /// </summary>
    [HttpGet("{userId}/roles")]
    public async Task<ActionResult<IEnumerable<string>>> GetUserRoles(Guid userId)
    {
        try
        {
            var roles = await _userService.GetUserRolesAsync(userId);
            return Ok(roles);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取用户角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 为用户分配角色
    /// </summary>
    [HttpPost("{userId}/roles/assign")]
    public async Task<ActionResult> AssignRolesToUser(Guid userId, [FromBody] IEnumerable<Guid> roleIds)
    {
        try
        {
            var result = await _userService.AssignRolesToUserAsync(userId, roleIds);
            if (!result)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return Ok(new { message = "角色分配成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "分配角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 移除用户的角色
    /// </summary>
    [HttpPost("{userId}/roles/remove")]
    public async Task<ActionResult> RemoveRolesFromUser(Guid userId, [FromBody] IEnumerable<Guid> roleIds)
    {
        try
        {
            var result = await _userService.RemoveRolesFromUserAsync(userId, roleIds);
            if (!result)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return Ok(new { message = "角色移除成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "移除角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 更新用户的角色（替换所有角色）
    /// </summary>
    [HttpPut("{userId}/roles")]
    public async Task<ActionResult> UpdateUserRoles(Guid userId, [FromBody] IEnumerable<Guid> roleIds)
    {
        try
        {
            var result = await _userService.UpdateUserRolesAsync(userId, roleIds);
            if (!result)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return Ok(new { message = "用户角色更新成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "更新用户角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 获取用户的所有权限
    /// </summary>
    [HttpGet("{userId}/permissions")]
    public async Task<ActionResult<IEnumerable<string>>> GetUserPermissions(Guid userId)
    {
        try
        {
            var permissions = await _userService.GetUserPermissionsAsync(userId);
            return Ok(permissions);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取用户权限失败", error = ex.Message });
        }
    }

    [HttpPost("create-demo")]
    public async Task<IActionResult> CreateUserDemo()
    {
        try
        {
            _logger.LogInformation("开始创建演示用户...");
            
            // 创建演示用户
            var userDto = new UserDto
            {
                UserName = $"demo_user_{DateTime.Now:yyyyMMdd_HHmmss}",
                Email = $"demo_{DateTime.Now:yyyyMMdd_HHmmss}@example.com",
                Password = "demo123",
                PhoneNumber = "13800138000",
                AvatarUrl = "https://example.com/avatar.jpg",
                Status = "active"
            };

            var createdUser = await _userService.CreateUserAsync(userDto);
            
            _logger.LogInformation($"演示用户创建成功: {createdUser.UserName}");
            
            return Ok(new { 
                message = "演示用户创建成功，请查看控制台输出以查看领域事件",
                user = createdUser,
                timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建演示用户失败");
            return StatusCode(500, new { 
                message = "创建演示用户失败", 
                error = ex.Message,
                timestamp = DateTime.UtcNow 
            });
        }
    }

    [HttpPost("update-status-demo")]
    public async Task<IActionResult> UpdateUserStatusDemo([FromBody] UpdateStatusRequest request)
    {
        try
        {
            _logger.LogInformation($"开始更新用户状态演示: 用户ID={request.UserId}, 新状态={request.NewStatus}");
            
            var result = await _userService.UpdateUserStatusAsync(request.UserId, request.NewStatus);
            
            if (result)
            {
                _logger.LogInformation("用户状态更新成功");
                return Ok(new { 
                    message = "用户状态更新成功，请查看控制台输出以查看领域事件",
                    userId = request.UserId,
                    newStatus = request.NewStatus,
                    timestamp = DateTime.UtcNow
                });
            }
            else
            {
                return BadRequest(new { 
                    message = "用户状态更新失败，用户可能不存在", 
                    userId = request.UserId,
                    timestamp = DateTime.UtcNow 
                });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新用户状态演示失败");
            return StatusCode(500, new { 
                message = "更新用户状态演示失败", 
                error = ex.Message,
                timestamp = DateTime.UtcNow 
            });
        }
    }

    [HttpGet("test-events")]
    public async Task<IActionResult> TestDomainEvents()
    {
        try
        {
            _logger.LogInformation("开始测试领域事件系统...");
            
            var result = await _userService.TestDomainEventsAsync();
            
            if (result)
            {
                return Ok(new { 
                    message = "领域事件测试成功", 
                    timestamp = DateTime.UtcNow,
                    note = "请查看控制台输出以查看事件详情"
                });
            }
            else
            {
                return BadRequest(new { 
                    message = "领域事件测试失败", 
                    timestamp = DateTime.UtcNow 
                });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "测试领域事件时发生错误");
            return StatusCode(500, new { 
                message = "测试领域事件时发生错误", 
                error = ex.Message,
                timestamp = DateTime.UtcNow 
            });
        }
    }
}

public class UpdateStatusRequest
{
    public Guid UserId { get; set; }
    public string NewStatus { get; set; } = string.Empty;
} 